from django.shortcuts import render, HttpResponse
from BASE.interface import get_backend_data as backend


# Create your views here.
class Index:
    __index_html = 'Index/index.html'
    __search_html = "Index/search.html"

    def index_view(self, request):
        collection_form_data = {
            "function": "Showrank",
            "rank": "collection"
        }
        read_form_data = {
            "function": "Showrank",
            "rank": "read"
        }
        comics_carousel = self.__get_comics_data(form_data={"function": "Showtopthree"})
        novels_carousel = self.__get_novels_data(form_data={"function": "Showtopthree"})
        comics_collection_rank = self.__get_comics_data(form_data=collection_form_data)
        comics_read_rank = self.__get_comics_data(form_data=read_form_data)
        novels_collection_rank = self.__get_novels_data(form_data=collection_form_data)
        novels_read_rank = self.__get_novels_data(form_data=read_form_data)
        return render(request, self.__index_html, context={
            "comics_carousel": comics_carousel,
            "novels_carousel": novels_carousel,
            "comics_collection_rank": comics_collection_rank,
            "comics_read_rank": comics_read_rank,
            "novels_collection_rank": novels_collection_rank,
            "novels_read_rank": novels_read_rank
        })
        pass

    def search_view(self, request):
        keyword = None
        if request.method == "GET":
            keyword = request.GET.get("keyword", "")
        comics_search_result = self.__get_comics_data(form_data={
            "function": "Showfindcom",
            "cName": keyword
        })
        novels_search_result = self.__get_novels_data(form_data={
            "function": "Showfindfic",
            "fName": keyword
        })
        sum_result = 0
        if comics_search_result is not None:
            sum_result = len(comics_search_result) + sum_result
        if novels_search_result is not None:
            sum_result = len(novels_search_result) + sum_result
        return render(request, self.__search_html, context={
            "comics_search_result": comics_search_result,
            "novels_search_result": novels_search_result,
            "sum_result": sum_result,
            "keyword": keyword
        })
        pass

    def __get_comics_data(self, url="http://193.112.72.237/Web-comfun/web/index.php?r=commic/index", form_data=None):
        return backend.get_comic_data(url, form_data)
        pass

    def __get_novels_data(self, url="http://193.112.72.237/Web-comfun/web/index.php?r=fiction/index", form_data=None):
        return backend.get_novels_data(url, form_data)
        pass


index_view = Index()
